package com.bong.panpan.bongcharttools.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.bong.panpan.bongcharttools.R;
import com.bong.panpan.bongcharttools.adapter.DeviceListAdapter;
import com.bong.panpan.bongcharttools.ble.BleDeviceState;
import com.bong.panpan.bongcharttools.ble.BleInfo;
import com.bong.panpan.bongcharttools.custom.MyUtil;
import com.bong.panpan.bongcharttools.custom.SpUtil;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class ScanFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @InjectView(R.id.scan_btn)
    Button scanBtn;
    @InjectView(R.id.refresh_btn)
    Button refreshBtn;
    @InjectView(R.id.radioButton3)
    RadioButton radioButton3;
    @InjectView(R.id.radioButton2)
    RadioButton radioButton2;
    @InjectView(R.id.radioButton1)
    RadioButton radioButton1;
    @InjectView(R.id.rssi_radio)
    RadioGroup rssiRadio;
    @InjectView(R.id.filter_edit)
    EditText filterEdit;
    @InjectView(R.id.cls_btn)
    Button clsBtn;
    @InjectView(R.id.device_list)
    ListView deviceList;
    private List<ScanFilter> scanFilters;
    private ScanSettings scanSettings;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnScanFragmentListener mListener;
    private Handler handler = new Handler();

    public ScanFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ScanFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ScanFragment newInstance(String param1, String param2) {
        ScanFragment fragment = new ScanFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_scan, container, false);
        ButterKnife.inject(this, view);
        init();
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnScanFragmentListener) {
            mListener = (OnScanFragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopScan();
        ButterKnife.reset(this);
    }

    @OnClick({R.id.scan_btn, R.id.refresh_btn, R.id.cls_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.scan_btn:
                scanClick(view);
                break;
            case R.id.refresh_btn:
                refreshClick(view);
                break;
            case R.id.cls_btn:
                clearClick(view);
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnScanFragmentListener {
        // TODO: Update argument type and name
        void onDeviceConnectClick(BleInfo bleInfo, BluetoothDevice device);

        void onDeviceDisConnectClick(BleInfo bleInfo, BluetoothDevice device);
    }

    private DeviceListAdapter adapter;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager bluetoothManager;
    private int sortModel = 2;
    private ScanCallback scanCallback = new ScanCallback() {
        /**
         * Callback when a BLE advertisement has been found.
         *
         * @param callbackType Determines how this callback was triggered. Could be one of
         *                     {ScanSettings#CALLBACK_TYPE_ALL_MATCHES},
         *                     {ScanSettings#CALLBACK_TYPE_FIRST_MATCH} or
         *                     {ScanSettings#CALLBACK_TYPE_MATCH_LOST}
         * @param result       A Bluetooth LE scan result.
         */
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            String mac = device.getAddress();
            String name = device.getName();
            int rssi = result.getRssi();
            BleInfo value;
            String filter = filterEdit.getText().toString();
            if (adapter.isDataExits(mac)) {
                adapter.modifyData(mac, rssi);
            } else {
                value = new BleInfo();
                value.name = name;
                value.mac = mac;
                value.rssi = rssi;
                if (MyUtil.isContainHeartRateServer(result.getScanRecord().getBytes()))
                    value.type = 1;
                else
                    value.type = 0;
                adapter.addData(value);
            }
            listFilterDeal(filter);
        }

        /**
         * Callback when scan could not be started.
         *
         * @param errorCode Error code (one of SCAN_FAILED_*) for scan failure.
         */
        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };

    private void bubbleSort() {
        adapter.sortData(sortModel);
    }

    private void init() {
        int id = SpUtil.getInstance().getInt("DeviceSelectHelper:rssiRadio", R.id.radioButton1);
        rssiRadio.check(id);
        switch (id) {
            case R.id.radioButton3:
                sortModel = 0;
                break;
            case R.id.radioButton2:
                sortModel = 1;
                break;
            case R.id.radioButton1:
                sortModel = 2;
                break;
        }
        adapter = new DeviceListAdapter(getActivity());
        adapter.setClickListener(this);
        deviceList.setAdapter(adapter);
        rssiRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.radioButton3:
                        sortModel = 0;
                        bubbleSort();
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.radioButton2:
                        sortModel = 1;
                        bubbleSort();
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.radioButton1:
                        sortModel = 2;
                        break;
                }
                SpUtil.getInstance().setInt("DeviceSelectHelper:rssiRadio", checkedId);
            }
        });
        filterEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                listFilterDeal(s.toString());
            }
        });
        initBle();
    }

    private void initBle() {
        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        bluetoothManager =
                (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            getActivity().finish();
            return;
        }
        mBluetoothAdapter.enable();
    }

    Runnable stopScan = new Runnable() {
        @Override
        public void run() {
            if ("正在扫描".equals(scanBtn.getText().toString())) {
                scanBtn.setText("扫描");
                mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
            }
        }
    };

    public void beginScan() {
        if (scanBtn.getText().equals("扫描")) {
            scanBtn.setText("正在扫描");
            if (scanFilters != null && scanSettings != null)
                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
            else
                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
            handler.postDelayed(stopScan, 60000);//60s后停止扫描
        } else {

        }
    }

    public void stopScan() {
        if (scanBtn.getText().equals("扫描")) {

        } else {
            handler.removeCallbacks(stopScan);
            scanBtn.setText("扫描");
            mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
        }
    }

    public void scanClick(View v) {
        if (scanBtn.getText().equals("扫描")) {
            scanBtn.setText("正在扫描");
            if (scanFilters != null && scanSettings != null)
                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
            else
                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
            handler.postDelayed(stopScan, 60000);//60s后停止扫描
        } else {
            scanBtn.setText("扫描");
            mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
        }
    }

    public void refreshClick(View v) {
        handler.removeCallbacks(stopScan);
        adapter.clear();
        adapter.notifyDataSetChanged();
        if (scanBtn.getText().equals("扫描")) {
            scanBtn.setText("正在扫描");
            if (scanFilters != null && scanSettings != null)
                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, scanSettings, scanCallback);
            else
                mBluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
        }
        handler.postDelayed(stopScan, 60000);//60s后停止扫描
    }

    public void clearClick(View v) {
        filterEdit.setText("");
    }

    private void listFilterDeal(String filter) {
        bubbleSort();
        adapter.setFilter(filter);
        adapter.notifyDataSetChanged();
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        int position = v.getId();
        BleInfo bleInfo = adapter.getItem(position);
        BluetoothDevice device = bluetoothManager.getAdapter().getRemoteDevice(bleInfo.mac);
        if (bleInfo.state == BleDeviceState.DEVICE_STATE_DISLINK) {
            //连接蓝牙
            if (mListener != null) {
                bleInfo.state = BleDeviceState.DEVICE_STATE_NONE;
                adapter.notifyDataSetChanged();
                mListener.onDeviceConnectClick(bleInfo, device);
            }
        }
        if (bleInfo.state == BleDeviceState.DEVICE_STATE_LINKED) {
            //连接蓝牙
            if (mListener != null) {
                bleInfo.state = BleDeviceState.DEVICE_STATE_NONE;
                adapter.notifyDataSetChanged();
                mListener.onDeviceDisConnectClick(bleInfo, device);
            }
        }
    }

    public void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
    }

    private void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
    }

    public void setScanParams(List<ScanFilter> scanFilters, ScanSettings scanSettings) {
        this.scanFilters = scanFilters;
        this.scanSettings = scanSettings;
    }
}
